<?php

class WikiPage extends MyModel
{
    /**
     * The followings are the available columns in table 'tbl_post':
     * @var integer $id
     * @var integer $wikiBookId
     * @var string $title
     * @var string $content
     * @var string $tags
     * @var integer $status
     */
    const STATUS_DRAFT=1;
    const STATUS_PUBLISHED=2;
    const STATUS_ARCHIVED=3;

    private $_oldTags;

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{WikiPage}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, status', 'required'),
            array('status', 'in', 'range'=>array(1,2,3)),
            array('title', 'length', 'max'=>128),
            array('tags', 'match', 'pattern'=>'/^[\w\s,]+$/', 'message'=>Yii::t('site','Tags can only contain word characters.')),
            array('tags', 'normalizeTags'),
            array('wikiBookId, content','safe'),

            array('title, content, status, tags', 'safe', 'on'=>'search'),
        );
    }
    // {{{ behaviors
    public function behaviors()
    {
        return array(
            'Timestamp2Behavior' => array(
                'class' => 'application.components.behaviors.Timestamp2Behavior',
            )
        );
    } // }}} 
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'wikiBook' => array(self::BELONGS_TO, 'WikiBook','wikiBookId'),
            'timestamp' => array(self::HAS_ONE,'ARTimeStamp','foreignKey','condition'=>"timestamp.tableName='WikiPage'"),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id'            => Yii::t('site','ID'),
            'wikiBookId'    => Yii::t('site','Wiki Book'),
            'title'         => Yii::t('site','Title'),
            'content'       => Yii::t('site','Content'),
            'tags'          => Yii::t('site','Tags'),
            'status'        => Yii::t('site','Status'),
        );
    }

    /**
     * @param integer the maximum number of posts that should be returned
     * @return array the most recently published posts
     */
    public function findRecentPages($limit=10)
    {
        return $this->findAll(
            array(
                'condition'=>'t.status='.self::STATUS_PUBLISHED,
                'order'=>'t.create_time DESC',
                'limit'=>$limit,
            )
        );
    }

    /**
     * @return string the URL that shows the detail of the post
     */
    public function getUrl()
    {
        return Yii::app()->createUrl('wikiPage/view', array(
            'id'=>$this->id,
            'title'=>$this->title,
            'WikiPage[show_content]'=>1,
        ));
    }

    /**
     * @return array a list of links that point to the post list filtered by every tag of this post
     */
    public function getTagLinks($showOnlineHelpTags=false)
    {
        $links=array();
        foreach(WikiPageTag::string2array($this->tags) as $tag) {
            if(!$showOnlineHelpTags and preg_match("/^Action_/", $tag)) {
            } else {
                $links[]=CHtml::link(CHtml::encode($tag), array('wikiPage/index', 'tag'=>$tag));
            }
        }
        return $links;
    }

    /**
     * Normalizes the user-entered tags.
     */
    public function normalizeTags($attribute,$params)
    {
        $this->tags=WikiPageTag::array2string(array_unique(WikiPageTag::string2array($this->tags)));
    }

    /**
     * This is invoked when a record is populated with data from a find() call.
     */
    protected function afterFind()
    {
        parent::afterFind();
        $this->_oldTags=$this->tags;
    }

    /**
     * This is invoked after the record is saved.
     */
    protected function afterSave()
    {
        parent::afterSave();
        WikiPageTag::model()->updateFrequency($this->_oldTags, $this->tags);
    }

    /**
     * This is invoked after the record is deleted.
     */
    protected function afterDelete()
    {
        parent::afterDelete();
        WikiPageTag::model()->updateFrequency($this->tags, '');
    }

    /**
     * Retrieves the list of posts based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the needed posts.
     */
    public function search()
    {
        $criteria=new CDbCriteria;

        $criteria->with = array('wikiBook');
        $criteria->compare('title',$this->title,true);
        $criteria->compare('content',$this->content,true);
        $criteria->compare('wikiBookId',$this->wikiBookId);
        $criteria->compare('tags',$this->tags,true);

        return new CActiveDataProvider('WikiPage', array(
            'criteria'=>$criteria,
            'sort'=>array(
                'attributes' => array(
                    'wikiBook'=>'wikiBook.name',
                    '*'
                ),
                'defaultOrder'=>'status',
            ),
        ));
    }
}
